//
//  NSString+AES256.m
//  Exchange
//
//  Created by ggcy on 16/6/30.
//  Copyright © 2016年 JND. All rights reserved.
//

#import "NSString+KNAES256.h"
#import "NSData+KNAES256.h"

@implementation NSString (KNAES256)
-(NSString *)KNAes256_encrypt:(NSString *)key iv:(NSString *)iv
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    //对数据进行加密
    NSData *result = [data KNAes256_encrypt:key iv: iv];
    
    //转换为2进制字符串
    if (result && result.length > 0) {
        
//        Byte *datas = (Byte*)[result bytes];
//        NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
//        for(int i = 0; i < result.length; i++){
//            [output appendFormat:@"%02x", datas[i]];
//        }
//        return output;
        return [[NSString alloc]initWithData:[result base64EncodedDataWithOptions:0] encoding:NSUTF8StringEncoding];
    }
    return nil;
}

-(NSString *)KNAes256_decrypt:(NSString *)key iv:(NSString *)iv
{
    //转换为2进制Data
//    NSMutableData *data = [NSMutableData dataWithCapacity:self.length / 2];
//    unsigned char whole_byte;
//    char byte_chars[3] = {'\0','\0','\0'};
//    int i;
//    for (i=0; i < [self length] / 2; i++) {
//        byte_chars[0] = [self characterAtIndex:i*2];
//        byte_chars[1] = [self characterAtIndex:i*2+1];
//        whole_byte = strtol(byte_chars, NULL, 16);
//        [data appendBytes:&whole_byte length:1];
//    }
    NSData *base64DecodeData=[[NSData alloc]initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    //对数据进行解密
    NSData* result = [base64DecodeData KNAes256_decrypt:key iv:iv];
    if (result && result.length > 0) {
        return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    }
    return nil;
}
@end
